from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status
import pickle
import base64

from .serializers import CartSerializer, CartSKUSerializer, CartDeleteSerializer, CartSelectAllSerializer
from . import constants
from goods.models import SKU

# Create your views here.


class CartView(GenericAPIView):
    serializer_class = CartSerializer

    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')
        try:
            user = request.user
        except Exception:
            user = None
        if user and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)
        else:
            cart_str = request.COOKIES.get('cart')
            if cart_str:
                cart_str = cart_str.encode()
                cart_bytes = base64.b64decode(cart_str)
                cart_dict = pickle.loads(cart_bytes)
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                cart_dict[sku_id]['count'] += count
                cart_dict[sku_id]['selected'] = selected
            else:
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
            cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response = Response(serializer.data)
            response.set_cookie('cart', cart_cookie, constants.CART_COOKIE_EXPIRES)
            return response

    def get(self, request):
        """查询购物车"""
        # 判断用户登录状态
        try:
            user = request.user
        except Exception:
            user = None
        if user and user.is_authenticated:
            # 如果用户已登录，从redis中查询  sku_id  count selected
            redis_conn = get_redis_connection('cart')
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)
            redis_selected_cart = redis_conn.smembers('cart_selected_%s' % user.id)
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': count,
                    'selected': sku_id in redis_selected_cart
                }
        else:
            cart_cookie = request.COOKIES.get('cart')
            if cart_cookie:
                cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))
            else:
                cart_dict = {}
        sku_id_list = cart_dict.keys()
        sku_obj_list = SKU.objects.filter(id__in=sku_id_list)
        for sku in sku_obj_list:
            sku.count = cart_dict[sku.id]['count']
            sku.selected = cart_dict[sku.id]['selected']
        serializer = CartSKUSerializer(sku_obj_list, many=True)
        return Response(serializer.data)

    def put(self, request):
        """
                修改购物车数据
                """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)
        else:
            cookie_cart = request.COOKIES.get('cart')

            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                # 表示cookie中没有购物车数据
                cart_dict = {}
            response = Response(serializer.data)
            if sku_id in cart_dict:
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
                cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('cart', cart_cookie, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def delete(self, request):
        serializer = CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']
        try:
            user = request.user
        except Exception:
            user = None
        if user and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hdel('cart_%s' % user.id, sku_id)
            pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            cart_cookie = request.COOKIES.get('cart')
            if cart_cookie:
                cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))
            else:
                cart_dict = {}
            response = Response(serializer.data)
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('cart', cart_cookie, max_age=constants.CART_COOKIE_EXPIRES)
            return response


class CartSelectAllView(GenericAPIView):
    serializer_class = CartSelectAllSerializer

    def perform_authentication(self, request):
        pass

    def put(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        selected = serializer.validated_data['selected']
        try:
            user = request.user
        except Exception:
            user = None
        if user and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
            sku_id_list = redis_cart_dict.keys()
            if selected:
                redis_conn.sadd('cart_selected_%s' % user.id, *sku_id_list)
            else:
                redis_conn.srem('cart_selected_%s' % user.id, *sku_id_list)
            return Response({'message': 'ok'})
        else:
            cart_cookie = request.COOKIES.get('cart')
            if cart_cookie:
                cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))
            else:
                cart_dict = {}
            response = Response({'message': 'ok'})
            if cart_dict:
                for cart_dict_values in cart_dict.values():
                    cart_dict_values['selected'] = selected
                cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('cart', cart_cookie, max_age=constants.CART_COOKIE_EXPIRES)
            return response